#include <bits/stdc++.h>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Codec
{
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode *root)
    {
        if (root == nullptr)
        {
            return "";
        }
        string ret;
        ret += to_string(root->val);
        ret += " ";
        ret += serialize(root->left);
        ret += serialize(root->right);
        return ret;
    }

    // Decodes your encoded data to tree.
    TreeNode *deserialize(string data)
    {
        if (data.empty())
        {
            return nullptr;
        }
        auto ret = split(data);
        TreeNode *root = new TreeNode(ret[0]);
        for (int i = 1; i < ret.size(); ++i)
        {
            root = insert(root, ret[i]);
        }
        return root;
    }

private:
    TreeNode *insert(TreeNode *root, int val)
    {
        if (root == nullptr)
        {
            return new TreeNode(val);
        }
        else if (val > root->val)
        {
            root->right = insert(root->right, val);
        }
        else
        {
            root->left = insert(root->left, val);
        }
        return root;
    }
    vector<int> split(string data)
    {
        vector<int> ret;
        char *tmp = const_cast<char *>(data.c_str());
        char *s = strtok(tmp, " ");
        while (s)
        {
            ret.push_back(atoi(s));
            s = strtok(nullptr, " ");
        }
        return ret;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec* ser = new Codec();
// Codec* deser = new Codec();
// string tree = ser->serialize(root);
// TreeNode* ans = deser->deserialize(tree);
// return ans;